<?php

namespace app\commission;

use app\models\City;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;

/**
 * 返佣
 *
 * Class ReturnCommission
 * @package app\commission
 */
class C2
{
    protected $user;
    protected $order;
    protected $set;

    public function __construct(\app\models\order\Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        // repeat
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {

            // 分红
            // if ($this->payback()) {
            //     $this->profit();
            //     $this->teamProfit();
            //     $this->diff();
            // }

            $this->profit();
            $this->teamProfit();
            $this->diff();

            // 新增复购平级奖, 只对合伙人有
            $this->repeatEqual();

            // $this->payback2();
            // 取消复购回本
            $list = UserCommission::find()
                ->where(['order_id' => $this->order->id])
                ->andWhere(['status' => 0])
                ->all();
            $this->_payback2($list);

        }

        // report
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {

            // if ($this->payback()) {
            //
            //     // 分红, 团队分红
            //     $this->profit();
            //     $this->teamProfit();
            //
            //     // 补贴
            //     $this->support();
            //
            //     // 推3加1
            //     $this->a31();
            //
            //     // 推合伙人, 董事
            //     $this->svip();
            //
            //     // 平级奖
            //     // $this->equal();
            //
            //     // 2 + 1
            //     $this->a21();
            // }

            // 分红, 团队分红
            $this->profit(true);
            $this->teamProfit(true);

            // 补贴
            $this->supportNew();

            // 推3加1
            $this->a31();

            // 推合伙人, 董事
            $this->svip();

            // 平级奖
            // $this->equal();

            // 2 + 1
            $this->a21();

            $this->payback2();
        }

        // 报单区才有佣金
        // if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
        //
        //     // 商品佣金
        //     $this->productCommission();
        //
        //     // 首购 与 复购
        //     // if ($this->user->repeat == 0) {
        //     if (!Product::checkRepeat($this->user, $this->order->id)) {
        //         $this->report();
        //
        //         // 记录首购
        //         $this->user->repeat = 1;
        //         $this->user->save();
        //     } else {
        //         $this->repeat();
        //     }
        // }
    }

    // 04-03 新增
    public function _repeatEqual($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    private function repeatEqual()
    {
        $type = 101;
        $name = '复购千万补贴';

        // 下单人要是合伙人
        if ($this->user->level == UserLevel::$keys['svip2']) {
            $r = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip2']], true);
            if ($r) {
                $r1 = $r[0];

                $commission = $this->_repeatEqual('repeat_1');
                $this->saveCommission($r1->id, $this->order->user_id, $this->order->id, $commission, $type, $name);

                if (count($r) >= 2) {
                    $r2 = $r[1];

                    $commission = $this->_repeatEqual('repeat_2');
                    $this->saveCommission($r2->id, $this->order->user_id, $this->order->id, $commission, $type, $name);
                }
            }
        }
    }

    // 04-03 报单, 新增平级 (相当于把之前的平级弄成了两层)
    private function baoEqual($user, $commission)
    {
        $type = 102;
        $name = '千万补贴';

        $r = Chain::getReferrer($user['id'], true);
        if ($r && $user['level'] == $r->level && in_array($r->level, [
            UserLevel::$keys['svip1'],
            UserLevel::$keys['svip2'],
            UserLevel::$keys['svip3']
        ])) {
            $c = $commission / 10;
            $this->saveCommission($r->id, $this->order->user_id, $this->order->id, $c, $type, $name);
        }
    }

    // 获取真正拿间推奖的人(出局处理)
    public function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级
        if ($the_referrer->level >= UserLevel::$keys['svip1']) {
            return $the_referrer;
        }

        // 如果推荐人是股东(这里改成>=号, 是因为有更多高级等级)
        // if ($the_referrer->level == UserLevel::$keys['vip2']) {
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {
            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            // var_dump($children);exit;

            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);

    }

    // 2 + 1
    public function a21()
    {
        $award = [
            [1, '直推'],
            [2, '间推'],

            [3, '平级奖'],
        ];

        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        foreach ($order_items as $item) {
            $product = Product::findOne(['id' => $item['product_id']]);

            // var_dump($product->price, $this->set->vip1, $this->set->svip1);exit;

            // 必须是521产品
            // 这里改了, 大于499就行了, 并且小于4980
            // if ($product->price == $this->set->vip1) {
            if ($product->price >= $this->set->vip1 && $product->price < $this->set->svip1) {

                $referrer = Chain::getReferrer($this->user->id, true);

                if ($referrer) {

                    // 门店
                    if ($referrer->level == UserLevel::$keys['vip1']) {
                        $commission = $this->set->vip1_recommend;

                        $commission *= $item['quantity'];
                        $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $commission, $award[0][0], $award[0][1]);

                        // 间推
                        $the_referrer = $this->getIndirect($referrer->id);
                        // var_dump($the_referrer);exit;
                        if ($the_referrer) {
                            $commission = $this->set->vip2_recommend - $this->set->vip1_recommend;

                            // var_dump($this->set->vip2_recommend , $this->set->vip1_recommend);exit;

                            $commission *= $item['quantity'];
                            $this->saveCommission($the_referrer['id'], $this->order->user_id, $this->order->id, $commission, $award[1][0], $award[1][1]);

                            // 平级奖 (培训大使, 合伙人, 董事, 就不拿了)
                            // $with_referrer =  Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
                            // $with_referrer =  Chain::getReferrerChainOne($the_referrer->id, [
                            //     // UserLevel::$keys['vip2'],
                            //     // UserLevel::$keys['svip1'],
                            //     // UserLevel::$keys['svip2'],
                            //     $the_referrer->level
                            // ]);
                            // 改成了找直推
                            $with_referrer = Chain::getReferrer($the_referrer->id, true);
                            if ($with_referrer && $with_referrer->level == $the_referrer->level) {
                                // $commission = $commission * $this->set->equal_vip2 / 100;
                                $commission = $commission * $this->_getEqualAward($with_referrer) / 100;
                                $this->saveCommission($with_referrer['id'], $this->order->user_id, $this->order->id, $commission, $award[2][0], $award[2][1]);

                                // 新增 平级奖
                                // $this->baoEqual($with_referrer, $commission);
                            }
                        }
                    }

                    // 老板
                    // if ($referrer->level == UserLevel::$keys['vip2']) {
                    if (in_array($referrer->level, [
                        UserLevel::$keys['vip2'],
                        UserLevel::$keys['svip1'],
                        UserLevel::$keys['svip2'],
                        UserLevel::$keys['svip3']
                    ])) {
                        // $commission = $this->set->vip2_recommend;
                        // 这是特殊处理
                        $commission = $this->set->vip2_recommend - $this->set->vip1_recommend;

                        $commission *= $item['quantity'];
                        $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $commission, $award[0][0], $award[0][1]);

                        // 平级奖 (培训大使, 合伙人, 董事, 就不拿了)
                        // $with_referrer =  Chain::getReferrerChainOne($referrer->id, [UserLevel::$keys['vip2']]);
                        // $with_referrer =  Chain::getReferrerChainOne($referrer->id, [
                        //     // UserLevel::$keys['vip2'],
                        //     // UserLevel::$keys['svip1'],
                        //     // UserLevel::$keys['svip2'],
                        //     $referrer->level
                        // ]);
                        // 改成了找直推
                        $with_referrer = Chain::getReferrer($referrer->id, true);
                        if ($with_referrer && $with_referrer->level == $referrer->level) {
                            // $commission = $commission * $this->set->equal_vip2 / 100;
                            $commission = $commission * $this->_getEqualAward($with_referrer) / 100;
                            $this->saveCommission($with_referrer['id'], $this->order->user_id, $this->order->id, $commission, $award[2][0], $award[2][1]);

                            // 新增 平级奖
                            // $this->baoEqual($with_referrer, $commission);
                        }
                    }
                }
            }
        }
    }

    // 新平级奖
    public function equalNew($user, $commission, $has_second = false)
    {
        $the_user = Chain::getReferrer($user->id, true);
        if ($the_user && $the_user->level == $user->level) {
            $commission = $commission * $this->_getEqualAward($the_user) / 100;

            $this->saveCommission($the_user['id'], $this->order->user_id, $this->order->id, $commission, '55', '平级奖');

            if ($has_second) {
                // 新增 平级奖
                $this->baoEqual($the_user, $commission);
            }
        }
    }

    protected function _getEqualAward($user)
    {
        if ($user->level == UserLevel::$keys['vip2']) {
            return $this->set->equal_vip2;
        }
        if ($user->level == UserLevel::$keys['svip1']) {
            return $this->set->equal_svip1;
        }
        if ($user->level == UserLevel::$keys['svip2']) {
            return $this->set->equal_svip2;
        }

        // 董事没有平级奖

        return 0;
    }

    // 平级奖 (有别于2+1的平级奖)
    // warn: 这个没有用了, 平级已经写在其它奖中了
    public function equal()
    {
        $award_name = '平级奖';
        $award_type = 7;

        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['svip1'],
            UserLevel::$keys['svip2']
        ], true);

        foreach ($chain as $user) {
            if ($user->level > $this->user->level) {
                break;
            } else if ($user->level < $this->user->level) {
                continue;
            } else {

                $commission = 0;

                if ($user->level == UserLevel::$keys['svip1']) {
                    $commission = $this->set->equal_svip1;
                }
                if ($user->level == UserLevel::$keys['svip2']) {
                    $commission = $this->set->equal_svip2;
                }

                // 比例
                $commission = $commission * $total_amount / 100;

                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                break;
            }
        }
    }

    // 推合人, 董事
    public function svip()
    {
        $award_name = '销售提成';
        $award_type = 8;

        $award_name2 = '平级奖';
        $award_type2 = 7;

        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        foreach ($order_items as $item) {
            $product = Product::findOne(['id' => $item['product_id']]);

            // 董事
            if ($product->price == $this->set->svip3) {
                $chain = Chain::getReferrerChain($this->order->user_id, [
                    UserLevel::$keys['svip3']
                ], true);
                if ($chain) {
                    $chain = $chain[0];
                    $commission = $this->set->svip3_recommend;

                    $commission *= $item['quantity'];
                    $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                }
            }

            // 合伙人
            if ($product->price == $this->set->svip2) {
                $chain = Chain::getReferrerChain($this->order->user_id, [
                    UserLevel::$keys['svip2'],
                    UserLevel::$keys['svip3']
                ], true);
                if ($chain) {
                    $chain = $chain[0];
                    if ($chain->level == UserLevel::$keys['svip2']) {
                        $commission = $this->set->svip2_recommend;
                    } else {
                        $commission = $this->set->svip3_recommend_svip2;
                    }

                    $commission *= $item['quantity'];
                    $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);

                    // 平级奖
                    $with_referrer = Chain::getReferrer($chain->id, true);
                    if ($with_referrer && $with_referrer->level == UserLevel::$keys['svip2']) {
                        $commission = $commission * $this->set->equal_svip2 / 100;
                        $this->saveCommission($with_referrer->id, $this->order->user_id, $this->order->id, $commission, $award_type2, $award_name2);

                        // 新增 平级奖
                        $this->baoEqual($with_referrer, $commission);
                    }
                }
            }
        }
    }

    // 推三返1
    public function a31()
    {
        // 商品这里设置的

        // 如果推的是 "培训大使" svip1
        $total_amount = $this->order->total_pay - $this->order->total_freight;
        $amount = $total_amount / $this->order->total_quantity;
        // var_dump($amount);exit;

        $award_name = '推三返一';
        $award_type = 9;

        $award_name2 = '平级奖';
        $award_type2 = 7;

        if ($amount == $this->set->svip1) {
            $chain = Chain::getReferrerChain($this->order->user_id, [
                UserLevel::$keys['svip1'],
                UserLevel::$keys['svip2'],
                UserLevel::$keys['svip3']
            ], true);
            if ($chain) {
                $chain = $chain[0];
                // 查询返奖次数
                $count = UserCommission::find()
                    ->where(['user_id' => $chain->id])
                    ->andWhere(['award_type' => $award_type])
                    ->count();
                $count = intval($count);
                if ($count > 0 && ($count + 1) % 3 === 0) {
                    $commission = $this->set->recommend_3;
                } else {
                    $commission = $this->set->recommend_1;
                }

                $commission *= $this->order->total_quantity;
                $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);

                // 平级奖
                $with_referrer = Chain::getReferrer($chain->id, true);
                // 改成了直推
                // if ($with_referrer && $with_referrer->level == UserLevel::$keys['svip1']) {
                if ($with_referrer && in_array($with_referrer->level, [UserLevel::$keys['svip1'], UserLevel::$keys['svip2'], UserLevel::$keys['svip3']])) {
                    $commission = $commission * $this->set->equal_svip1 / 100;
                    $this->saveCommission($with_referrer->id, $this->order->user_id, $this->order->id, $commission, $award_type2, $award_name2);

                    // 新增 平级奖
                    $this->baoEqual($with_referrer, $commission);
                }
            }
        }
    }

    protected function supportNew()
    {
        $vip2 = $this->_support('support_vip2');
        $svip1 = $this->_support('support_svip1');
        $svip2 = $this->_support('support_svip2');
        $svip3 = $this->_support('support_svip3');

        $award_name = '补贴';
        $award_type = 81;

        if ($vip2 > 0) {
            $vip2_count = User::findAll(['level' => UserLevel::$keys['vip2']]);
            if (count($vip2_count) > 0) {
                $vip2 /= count($vip2_count);

                foreach ($vip2_count as $user) {
                    $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $vip2, $award_type, $award_name);

                    // 新增平级奖
                    // $this->equalNew($user, $vip2);

                    // 修改两层
                    $this->equalNew($user, $vip2, true);
                }
            }
        }
        if ($svip1 > 0) {
            $svip1_count = User::findAll(['level' => UserLevel::$keys['svip1']]);
            if (count($svip1_count) > 0) {
                $svip1 /= count($svip1_count);

                foreach ($svip1_count as $user) {
                    $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $svip1, $award_type, $award_name . '-培训大使');

                    // 新增平级奖
                    // $this->equalNew($user, $svip1);

                    // 修改两层
                    $this->equalNew($user, $svip1, true);
                }
            }
        }
        if ($svip2 > 0) {
            $svip2_count = User::findAll(['level' => UserLevel::$keys['svip2']]);
            if (count($svip2_count) > 0) {
                $svip2 /= count($svip2_count);

                foreach ($svip2_count as $user) {
                    $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $svip2, $award_type, $award_name . '-合伙人');

                    // 新增平级奖
                    // $this->equalNew($user, $svip2);

                    // 修改两层
                    $this->equalNew($user, $svip2, true);
                }
            }
        }
        if ($svip3 > 0) {
            $svip3_count = User::findAll(['level' => UserLevel::$keys['svip3']]);
            if (count($svip3_count) > 0) {
                $svip3 /= count($svip3_count);

                // var_dump(count($svip3_count), $svip3);exit;

                foreach ($svip3_count as $user) {
                    $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $svip3, $award_type, $award_name . '-董事');

                    // 新增平级奖
                    // $this->equalNew($user, $svip3);

                    // 修改两层
                    $this->equalNew($user, $svip3, true);
                }
            }
        }
    }

    // 补贴
    protected function _support($support_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += $product[$support_key] * $item['quantity'];
        }

        return $sum;
    }

    public function support()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['svip1'],
            UserLevel::$keys['svip2'],
            UserLevel::$keys['svip3']
        ], true);

        $award_name = '培训补贴';
        $award_type = 11;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_svip1 = false;
        $has_svip2 = false;
        $has_svip3 = false;

        // 改成极差了
        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_svip1 = 0;
        $diff_svip2 = 0;
        $diff_svip3 = 0;

        foreach ($chain as $user) {
            if ((!$has_vip1 && !$has_vip2 && !$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['vip1']) {
                $commission = $this->_support('support_vip1');
                $diff_vip1 = $commission;
                // $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['vip2']) {
                $commission = $this->_support('support_vip2');
                $diff_vip2 = $commission - $diff_vip1;
                // $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['svip1']) {
                $commission = $this->_support('support_svip1');
                $diff_svip1 = $commission - $diff_vip2 - $diff_vip1;
                // $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip1, $award_type, $award_name);
                $has_svip1 = true;
            }
            if ((!$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['svip2']) {
                $commission = $this->_support('support_svip2');
                $diff_svip2 = $commission - $diff_svip1 - $diff_vip2 - $diff_vip1;
                // $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip2, $award_type, $award_name);
                $has_svip2 = true;
            }
            if (!$has_svip3 && $user->level == UserLevel::$keys['svip3']) {
                $commission = $this->_support('support_svip3');
                $diff_svip3 = $commission - $diff_svip2 - $diff_svip1 - $diff_vip2 - $diff_vip1;
                // var_dump($diff_svip3 , $diff_svip2 , $diff_svip1 , $diff_vip2 , $diff_vip1);exit;
                // $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, $award_type, $award_name);
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip3, $award_type, $award_name);
                $has_svip3 = true;
                break;
            }
        }

        // var_dump($support_vip1, $support_vip2, $support_svip1, $support_svip2, $support_svip3);exit;
    }

    // 回本
    public function payback()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip3']], true);
        if ($chain) {
            $chain = $chain[0];

            // get all commission
            $sum = UserCommission::find()
                ->where(['user_id' => $chain->id])
                ->sum('balance');
            $sum = floatval($sum);

            if ($sum >= $this->set->svip3_total) {
                return true;
            } else {
                $commission = $this->set->svip3_ratio * ($this->order->total_pay - $this->order->total_freight) / 100;
                $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, 30, '董事回本');

                return false;

                // debug
                // return true;
            }

            // var_dump($sum);exit;
        }

        return true;
    }

    public function payback2Old()
    {
        $list = UserCommission::find()
            ->where(['order_id' => $this->order->id])
            ->andWhere(['status' => 0])
            ->all();

        $chain = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip3']], true);
        if ($chain) {
            $chain = $chain[0];

            // get all commission
            $sum = UserCommission::find()
                ->where(['user_id' => $chain->id])
                ->andWhere(['status' => 1])
                ->sum('balance');
            $sum = floatval($sum);

            $await = UserCommission::find()
                ->where(['order_id' => $this->order->id])
                ->andWhere(['status' => 0])
                ->sum('balance');
            $await = floatval($await);

            // if ($sum >= $this->set->svip3_total) {
            if ($sum + $await >= $this->set->svip3_total) {

                // 处理待返佣金
                $this->_payback2($list);

            } else {

                // 回本
                $commission = $this->set->svip3_ratio * ($this->order->total_pay - $this->order->total_freight) / 100;
                // 这里只能用 > 大于号
                // if ($sum + $commission >= $this->set->svip3_total) {
                if ($sum + $commission > $this->set->svip3_total) {
                    // 处理待返佣金
                    $this->_payback2($list);
                } else {
                    $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, 30, '董事回本', 1);

                    // 删除佣金
                    foreach ($list as $item) {
                        $item->delete();
                    }
                }


            }
        } else {

            // 处理待返佣金
            $this->_payback2($list);
        }
    }

    // 只有董事直推的, 才做回本处理
    public function payback2()
    {
        $list = UserCommission::find()
            ->where(['order_id' => $this->order->id])
            ->andWhere(['status' => 0])
            ->all();

        // $chain = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip3']], true);
        $chain = Chain::getReferrer($this->order->user_id, true);
        if ($chain && $chain->level == UserLevel::$keys['svip3']) {
            // $chain = $chain[0];

            // get all commission
            $sum = UserCommission::find()
                ->where(['user_id' => $chain->id])
                ->andWhere(['status' => 1])
                ->sum('balance');
            $sum = floatval($sum);

            $await = UserCommission::find()
                ->where(['order_id' => $this->order->id])
                ->andWhere(['status' => 0])
                ->sum('balance');
            $await = floatval($await);

            // if ($sum >= $this->set->svip3_total) {
            if ($sum + $await > $this->set->svip3_total) {

                // 处理待返佣金
                $this->_payback2($list);

            } else {

                // 回本
                $commission = $this->set->svip3_ratio * ($this->order->total_pay - $this->order->total_freight) / 100;
                // 这里只能用 > 大于号
                // if ($sum + $commission >= $this->set->svip3_total) {
                if ($sum + $commission > $this->set->svip3_total) {
                    // 处理待返佣金
                    $this->_payback2($list);
                } else {
                    $this->saveCommission($chain->id, $this->order->user_id, $this->order->id, $commission, 30, '董事回本', 1);

                    // 删除佣金
                    foreach ($list as $item) {
                        $item->delete();
                    }
                }


            }
        } else {

            // 处理待返佣金
            $this->_payback2($list);
        }
    }

    public function _payback2($list)
    {
        // 处理待返佣金
        foreach ($list as $item) {
            $account = UserAccount::findOne(['user_id' => $item->user_id]);
            if ($account) {
                // $account->balance += $item->balance;
                // 改成待返
                $account->await_balance += $item->balance;
                $account->save();
            }

            // $item->status = 1;
            $item->status = 0;
            $item->save();
        }
    }

    // team profit
    // 这里改成极差了
    public function teamProfit($has_equal = false)
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $chain = Chain::getReferrerChain($this->order->user_id, [UserLevel::$keys['svip2'], UserLevel::$keys['svip3']], true);
        $has_svip2 = false;
        $has_svip3 = false;

        // 加上极差了
        $diff = 0;

        foreach ($chain as $user) {
            if (!$has_svip3 && $user->level == UserLevel::$keys['svip3']) {
                $commission = $this->set->team_profit_svip3 * $total_amount / 100;
                $commission -= $diff;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 22, '团队分红');

                // 新增平级奖
                if ($has_equal) {
                    // $this->equalNew($user, $commission);

                    // 修改两层
                    $this->equalNew($user, $commission, true);
                }

                $has_svip3 = true;
                break;
            }
            if (!$has_svip2 && $user->level == UserLevel::$keys['svip2']) {
                $commission = $this->set->team_profit_svip2 * $total_amount / 100;
                $diff = $commission;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 22, '团队分红');

                // 新增平级奖
                if ($has_equal) {
                    // $this->equalNew($user, $commission);

                    // 修改两层
                    $this->equalNew($user, $commission, true);
                }

                $has_svip2 = true;
            }
        }
    }

    // profit
    public function profit($has_equal = false)
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $svip2_list = User::find()
            ->where(['level' => UserLevel::$keys['svip2']])
            ->all();
        $svip3_list = User::find()
            ->where(['level' => UserLevel::$keys['svip3']])
            ->all();

        if ($svip2_list) {
            $commission = $this->set->profit_svip2 * $total_amount / count($svip2_list) / 100;
            foreach ($svip2_list as $user) {
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 21, '分红');

                // 新增平级奖
                if ($has_equal) {
                    // $this->equalNew($user, $commission);

                    // 修改两层
                    $this->equalNew($user, $commission, true);
                }
            }
        }
        if ($svip3_list) {
            $commission = $this->set->profit_svip3 * $total_amount / count($svip3_list) / 100;
            foreach ($svip3_list as $user) {
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $commission, 21, '分红');

                // 新增平级奖
                if ($has_equal) {
                    // $this->equalNew($user, $commission);

                    // 修改两层
                    $this->equalNew($user, $commission, true);
                }
            }
        }
    }

    // diff
    public function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;
        foreach ($order_items as $item) {
            // 这里可以不用商品原价, order_item中是折后价
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            // var_dump($product);exit;
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    public function diff()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [], true);

        $award_name = '复购差价';
        $award_type = 20;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_svip1 = 0;
        $diff_svip2 = 0;
        $diff_svip3 = 0;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_svip1 = false;
        $has_svip2 = false;
        $has_svip3 = false;

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('diff_vip1');
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('diff_vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_svip1 && !$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['svip1']) {
                $diff_svip1 = $this->_diff('diff_svip1');
                $diff_svip1 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip1, $award_type, $award_name);
                $has_svip1 = true;
            }
            if ((!$has_svip2 && !$has_svip3) && $user->level == UserLevel::$keys['svip2']) {
                $diff_svip2 = $this->_diff('diff_svip2');
                $diff_svip2 -= $diff_svip1 + $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip2, $award_type, $award_name);
                $has_svip2 = true;
            }
            if (!$has_svip3 && $user->level == UserLevel::$keys['svip3']) {
                $diff_svip3 = $this->_diff('diff_svip3');
                $diff_svip3 -= $diff_svip2 + $diff_svip1 + $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $this->order->user_id, $this->order->id, $diff_svip3, $award_type, $award_name);
                $has_svip3 = true;
                break;
            }
        }

        // var_dump($diff_vip1, $diff_vip2, $diff_svip1, $diff_svip2, $diff_svip3);exit;
    }



    // old ------------------------------------------------------


    // 处理出局 ( 前2个, 是没有间推奖的 )
    // protected function get2($user_id)
    // {
    //     // 需要找链上的合伙人(跳过区代)
    //     $vip2_one = Chain::getReferrerChainOne($user_id, [UserLevel::$keys['vip2']], true);
    //
    //     // 如果此人已经有2个直推 "代理", 则继续找上级
    //     if ($vip2_one) {
    //         $children = Chain::getChildrenLevel($vip2_one->id, [UserLevel::$keys['vip1'], UserLevel::$keys['vip2'], UserLevel::$keys['svip1'], UserLevel::$keys['svip2']]);
    //
    //         if ($children && count($children) > 2) {
    //             return $this->get2($vip2_one->id);
    //         } else {
    //             return $vip2_one;
    //         }
    //     }
    //
    //     return null;
    // }

    // todo 可能这个更正确
    public function getRealFinal($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 如果推荐人是股东
        if ($the_referrer->level == UserLevel::$keys['vip2']) {
            // 判断是否属于前2单
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getRealFinal($the_referrer->id);
                }
            } else {
                return $this->getRealFinal($the_referrer->id);
            }
        }

        return $this->getRealFinal($the_referrer->id);

    }

    // 获取真正拿间推奖的人(出局处理)
    protected function getReal($referrer_id)
    {
        // a -> b -> c 购买, 找 a
        // 找到订单推荐人的上级, 如果是 代理, 则找链上的合伙人
        // 否则, 判断推荐人是不是 合伙人的 前两个直推
        // 是, 继续找链上的合伙人
        // 否则, 就应该是此人(第3个推荐了)

        $the_referrer = Chain::getReferrer($referrer_id, true);
        if (!$the_referrer) {
            return null;
        }

        if ($the_referrer->level == UserLevel::$keys['vip2']) {
            // 如果是合伙人, 判断推荐是不是前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
            }
            // var_dump($children);exit;
            $in = in_array($referrer_id, $children);
            if ($in) {
                return Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
            } else {
                return $the_referrer;
            }

            // } else if ($the_referrer->level == UserLevel::$keys['vip1']) {
        } else {
            // 如果是代理, (区代,市代) , 则直接找链上的合伙人
            return Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
        }
    }

    // 首购奖
    protected function report()
    {
        $referrer = Chain::getReferrer($this->user->id, true);

        if ($referrer) {

            // 代理
            if ($referrer->level == UserLevel::$keys['vip1']) {

                // 直推奖
                $balance = $this->set['vip1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 11, '销售提成');

                $the_referrer = $this->getReal($referrer->id);
                if ($the_referrer) {

                    // 间推奖
                    $balance = $this->set['vip2_2'];
                    $this->saveCommission($the_referrer['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');

                    // 平级奖
                    $with_referrer =  Chain::getReferrerChainOne($the_referrer->id, [UserLevel::$keys['vip2']]);
                    // var_dump($the_referrer, $with_referrer);exit;
                    if ($with_referrer) {
                        $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                        $this->saveCommission($with_referrer['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                    }
                }

                // 需要找链上的合伙人(跳过区代)
                // $vip2_list = Chain::getReferrerChain($referrer->id, [UserLevel::$keys['vip2']], true);
                // if ($vip2_list) {
                //     // 间推奖
                //     $balance = $this->set['vip2_2'];
                //     $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');
                //
                //     if (count($vip2_list) >= 2) {
                //         // 平级奖
                //         // $balance = $this->set['vip2_2'];
                //         $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                //         $this->saveCommission($vip2_list[1]['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                //     }
                // }

                // $vip2_one = $this->get2($referrer->id);
                // // var_dump($vip2_one);exit;
                // if ($vip2_one) {
                //     // 间推奖
                //     $balance = $this->set['vip2_2'];
                //     $this->saveCommission($vip2_one['id'], $this->order->user_id, $this->order->id, $balance, 12, '销售提成');
                //
                //     // 平级奖
                //     $equal_one = Chain::getReferrerChainOne($vip2_one->id, [UserLevel::$keys['vip2']], true);
                //     if ($equal_one) {
                //         $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                //         $this->saveCommission($equal_one['id'], $this->order->user_id, $this->order->id, $balance, 13, '培训补助');
                //     }
                // }
            }

            // 合伙人
            if ($referrer->level == UserLevel::$keys['vip2']) {
                // 直推奖
                $balance = $this->set['vip2_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 21, '销售提成');

                // 需要找链上的合伙人(跳过区代)
                $vip2_list = Chain::getReferrerChain($referrer->id, [UserLevel::$keys['vip2']], true);
                if ($vip2_list) {
                    // 这里没有间推奖了, 只有平级奖
                    // $balance = $this->set['vip2_2'];
                    $balance = $this->set['vip2_1'] * $this->set['vip2_3'] / 100;
                    $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 23, '销售提成');

                    // // 间推奖
                    // $balance = $this->set['vip2_2'];
                    // $this->saveCommission($vip2_list[0]['id'], $this->order->user_id, $this->order->id, $balance, 22, '销售提成');
                    //
                    // if (count($vip2_list) >= 2) {
                    //     // 平级奖
                    //     // $balance = $this->set['vip2_2'];
                    //     $balance = $this->set['vip2_2'] * $this->set['vip2_3'] / 100;
                    //     $this->saveCommission($vip2_list[1]['id'], $this->order->user_id, $this->order->id, $balance, 23, '培训补助');
                    // }
                }
            }

            // 区代
            if ($referrer->level == UserLevel::$keys['svip1']) {
                // 直推奖
                $balance = $this->set['svip1_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 31, '销售提成');
            }

            // 市代
            if ($referrer->level == UserLevel::$keys['svip2']) {
                // 直推奖
                $balance = $this->set['svip2_1'];
                $this->saveCommission($referrer->id, $this->order->user_id, $this->order->id, $balance, 41, '销售提成');
            }
        }

        // 区域奖
        $area = $this->getAreaUser();
        if ($area[0]) {
            $balance = $this->set['svip1_2'];
            $this->saveCommission($area[0]['id'], $this->order->user_id, $this->order->id, $balance, 98, '区域奖');
        }
        if ($area[1]) {
            $balance = $this->set['svip2_2'];
            $this->saveCommission($area[1]['id'], $this->order->user_id, $this->order->id, $balance, 98, '区域奖');
        }
    }

    // 获取域区
    protected function getAreaUser()
    {
        $area_id = UserAddress::find()
            ->where(['id' => $this->order->user_address])
            ->select(['table_id'])
            ->scalar();
        $city_id = City::find()
            ->where(['area_id' => $area_id])
            ->select(['city_id'])
            ->scalar();

        $svip1 = User::find()
            ->where(['level' => UserLevel::$keys['svip1']])
            ->andWhere(['address_up' => $area_id])
            ->orderBy(['update_time' => SORT_DESC])
            ->one();
        $svip2 = User::find()
            ->where(['level' => UserLevel::$keys['svip2']])
            ->andWhere(['address_up' => $city_id])
            ->orderBy(['update_time' => SORT_DESC])
            ->one();

        // var_dump($area_id, $city_id);exit;

        return [$svip1, $svip2];
    }

    // 复购奖
    protected function repeat()
    {
        // 差价奖(上级 也是 repeat = 1 )
        // 用这种方式, 购物车也是正确的
        $vip1_price = $this->set['diff_vip1'];
        $vip2_price = $this->set['diff_vip2'];
        $svip1_price = $this->set['diff_svip1'];
        $svip2_price = $this->set['diff_svip2'];

        $current_price = $vip1_price;
        if ($this->user->level === UserLevel::$keys['vip2']) {
            $current_price = $vip2_price;
        }
        if ($this->user->level === UserLevel::$keys['svip1']) {
            $current_price = $svip1_price;
        }
        if ($this->user->level === UserLevel::$keys['svip2']) {
            $current_price = $svip2_price;
        }

        $diff_vip2 = 0;
        $diff_svip1 = 0;
        $diff_svip2 = 0;

        // 如果关系链是乱调的, 需要用foreach ....
        $chain = Chain::getReferrerChain($this->user->id,
            [UserLevel::$keys['vip2'], UserLevel::$keys['svip1'], UserLevel::$keys['svip2']],
            true);
        foreach ($chain as $u) {
            if ($u->level <= $this->user->level) {
                continue;
            }
            if (!$diff_svip2 && !$diff_svip1 && !$diff_vip2 && $u->level == UserLevel::$keys['vip2']) {
                $temp = $current_price - $vip2_price;
                if ($temp > 0) {
                    $diff_vip2 = $temp;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_vip2, 88, '复购差价');
                }
            }
            if (!$diff_svip2 && !$diff_svip1 && $u->level == UserLevel::$keys['svip1']) {
                $temp = $current_price - $svip1_price;
                if ($temp > 0) {
                    $diff_svip1 = $temp - $diff_vip2;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_svip1, 88, '复购差价');
                }
            }
            if (!$diff_svip2 && $u->level == UserLevel::$keys['svip2']) {
                $temp = $current_price - $svip2_price;
                if ($temp > 0) {
                    $diff_svip2 = $temp - $diff_svip1 - $diff_vip2;
                    $this->saveCommission($u->id, $this->order->user_id, $this->order->id, $diff_svip2, 88, '复购差价');
                    break;
                }
            }
        }

        // $vip2 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['vip2']]);
        // $svip1 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['svip1']]);
        // $svip2 = Chain::getReferrerChainOne($this->user->id, [UserLevel::$keys['svip2']]);
        //
        // if ($vip2 && $vip2->level > $this->user->level) {
        //     $temp = $current_price - $vip2_price;
        //     if ($temp > 0) {
        //         $diff_vip2 = $temp;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_vip2, 88, '复购差价');
        //     }
        // }
        // if ($svip1 && $svip1->level > $this->user->level) {
        //     $temp = $current_price - $svip1_price;
        //     if ($temp > 0) {
        //         $diff_svip1 = $temp - $diff_vip2;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_svip1, 88, '复购差价');
        //     }
        // }
        // if ($svip2 && $svip2->level > $this->user->level) {
        //     $temp = $current_price - $svip2_price;
        //     if ($temp > 0) {
        //         $diff_svip2 = $temp - $diff_svip1 - $diff_vip2;
        //         $this->saveCommission($vip2->id, $this->order->user_id, $this->order->id, $diff_svip2, 88, '复购差价');
        //     }
        // }

        // 区域奖
        $area = $this->getAreaUser();
        if ($area[0]) {
            $balance = $this->set['svip1_3'];
            $this->saveCommission($area[0]['id'], $this->order->user_id, $this->order->id, $balance, 99, '区域奖');
        }
        if ($area[1]) {
            $balance = $this->set['svip2_3'];
            $this->saveCommission($area[1]['id'], $this->order->user_id, $this->order->id, $balance, 99, '区域奖');
        }
    }

    // 总商品佣金列表
    protected function productCommission()
    {
        $list = [];
        $items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->with(['product.commissionDiff'])
            ->asArray()
            ->all();

        foreach ($items as &$item) {
            $commission = $item['product']['commissionDiff'];
            foreach ($commission as $key => &$c) {
                // 直推合伙人所有收益的 10%
                if ($key == 'vip2_3') {
                    // $c = $c * $commission['vip2_1'] / 100 / $item['quantity'];
                    continue;
                }

                // 数量
                $c = $c * $item['quantity'];
            }
            array_push($list, $commission);
        }

        /*
         * 每二维数组合成1维数组
         * array(1) {
          [0]=>
          array(16) {
            ["id"]=>
            int(11)
            ["product_id"]=>
            int(1008)
            ["vip1"]=>
            float(5000)
            ["vip2_1"]=>
            float(7000)
            ["vip2_2"]=>
            float(2000)
            ["vip2_3"]=>
            float(700)
            ["svip1_1"]=>
            float(7000)
            ["svip1_2"]=>
            float(300)
            ["svip1_3"]=>
            float(10)
            ["svip2_1"]=>
            float(7000)
            ["svip2_2"]=>
            float(1000)
            ["svip2_3"]=>
            float(15)
            ["diff_vip1"]=>
            float(400)
            ["diff_vip2"]=>
            float(340)
            ["diff_svip1"]=>
            float(300)
            ["diff_svip2"]=>
            &float(240)
          }
        }
         */
        $temp = [];
        foreach ($list as $value) {
            foreach ($value as $k => $v) {

                if ($k == 'product_id' || $k == 'id') {
                    continue;
                }

                if (key_exists($k, $temp)) {
                    $temp[$k] += $v;
                } else {
                    $temp[$k] = $v;
                }
            }
        }

        // var_dump($list, $temp);exit;
        $this->set = $temp;

    }

    // 保存佣金
    protected function saveCommission($user_id, $fans_id, $order_id, $balance, $type, $name, $status = 0)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            // $model->status = $status;
            $model->status = 0;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            if ($status == 1) {
                $account = UserAccount::findOne(['user_id' => $user_id]);
                if ($account) {
                    // $account->balance += $balance;
                    // 改成待返
                    $account->await_balance += $balance;
                    $account->save();
                }
            }

            // $account = UserAccount::findOne(['user_id' => $user_id]);
            // if ($account) {
            //     $account->balance += $balance;
            //     $account->save();
            // }
        }
    }

}